<?php

namespace helper;


class TpConfig
{


  /**
   * 设置参数
   * @param $name
   * @param $arr
   * @return bool
   */
  static public function write($name, $arr)
  {
    $path    = app()->getConfigPath() . $name . '.php';
    $arr     = self::format($arr);
    $content = <<<EOT
<?php
return $arr;
EOT;
    return file_put_contents($path, $content);
  }

  /**
   * 追加设置
   * @param $name
   * @param $append
   * @return false|int
   */
  static public function appendWrite($name, $append)
  {
    $arr = self::format(array_merge(config($name), $append));
    return self::write($name, $arr);
  }

  /**
   * 格式化数组
   * @param $var
   * @return false|string
   */
  static public function format($var)
  {
    $exporter = function ($var, $indent = "") use (&$exporter) {
      switch (gettype($var)) {
        case "string":
          return '"' . addcslashes($var, "\\\$\"\r\n\t\v\f") . '"';
        case "array":
          $self    = $exporter;
          $indexed = array_keys($var) === range(0, count($var) - 1);
          $r       = [];
          foreach ($var as $key => $value) {
            $r[] = "$indent    "
                . ($indexed ? "" : $self($key) . " => ")
                . $self($value, "$indent    ");
          }
          return "[\n" . implode(",\n", $r) . "\n" . $indent . "]";
        case "boolean":
          return $var ? "TRUE" : "FALSE";
        default:
          return var_export($var, true);
      }
    };
    ob_start();
    array_map(function ($var) use ($exporter) {
      echo $exporter($var);
    }, func_get_args());
    $arr = ob_get_contents();
    ob_end_clean();
    return $arr;
  }

}